package net.documentshare.question;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.documentshare.i.ICommonBeanAware;
import net.documentshare.impl.AItSiteAppclicationModule;
import net.documentshare.impl.AbstractAttention;
import net.simpleframework.ado.db.ExpressionValue;
import net.simpleframework.ado.db.IQueryEntitySet;
import net.simpleframework.ado.db.ITableEntityManager;
import net.simpleframework.ado.db.SQLValue;
import net.simpleframework.ado.lucene.AbstractLuceneManager;
import net.simpleframework.core.ExecutorRunnable;
import net.simpleframework.core.IInitializer;
import net.simpleframework.core.ITaskExecutorAware;
import net.simpleframework.core.ado.db.Table;
import net.simpleframework.core.bean.IIdBeanAware;
import net.simpleframework.organization.account.AccountSession;
import net.simpleframework.organization.account.IAccount;
import net.simpleframework.organization.component.login.LoginUtils;
import net.simpleframework.util.DateUtils;
import net.simpleframework.util.IoUtils;
import net.simpleframework.util.StringUtils;
import net.simpleframework.web.WebUtils;
import net.simpleframework.web.page.IPageConstants;
import net.simpleframework.web.page.PageRequestResponse;
import net.simpleframework.web.page.component.AbstractComponentBean;
import net.simpleframework.web.page.component.ComponentParameter;
import net.simpleframework.web.page.component.ui.tabs.EMatchMethod;
import net.simpleframework.web.page.component.ui.tabs.TabHref;
import net.simpleframework.web.page.component.ui.tabs.TabsUtils;

public class QuestionApplicationModule extends AItSiteAppclicationModule implements IQuestionApplicationModule {
	private String deployName = "question";

	@Override
	public void init(IInitializer initializer) {
		try {
			super.init(initializer);
			doInit(QuestionUtils.class, deployName);
			((ITaskExecutorAware) getApplication()).getTaskExecutor().addScheduledTask(60 * 10, DateUtils.DAY_PERIOD, new ExecutorRunnable() {
				@Override
				public void task() {
					QuestionUtils.doStatRebuild();
				}
			});
		} catch (Exception e) {
		}
	}

	@Override
	public Class<? extends IIdBeanAware> getEntityBeanClass() {
		return QuestionBean.class;
	}

	static final Table question = new Table("it_question");
	static final Table question_project = new Table("it_question_project");
	static final Table question_attention = new Table("it_question_attention");
	static final Table question_ext = new Table("it_question_ext");

	@Override
	protected void putTables(Map<Class<?>, Table> tables) {
		super.putTables(tables);
		tables.put(QuestionBean.class, question);
		tables.put(QuestionProjectBean.class, question_project);
		tables.put(QuestionAttention.class, question_attention);
		tables.put(QuestionExtBean.class, question_ext);
	}

	@Override
	public AbstractComponentBean getComponentBean(PageRequestResponse requestResponse) {
		return null;
	}

	@Override
	public String getViewUrl(Object id) {
		final StringBuilder sb = new StringBuilder();
		sb.append("/question").append("/v/").append(id);
		sb.append(".html");
		return sb.toString();
	}

	@Override
	protected Map<String, String> getOrderData() {
		Map<String, String> orderData = super.getOrderData();
		orderData.put("zero", "零回答");
		return orderData;
	}

	@Override
	public String tabs(PageRequestResponse requestResponse) {
		final List<TabHref> tabHrefs = new ArrayList<TabHref>();
		final String applicationUrl = getApplicationUrl(requestResponse);
		TabHref href = new TabHref("待解决的问答", WebUtils.addParameters(applicationUrl, "t=open"));
		href.setMatchMethod(EMatchMethod.startsWith);
		tabHrefs.add(href);
		href = new TabHref("已解决的问答", WebUtils.addParameters(applicationUrl, "t=closed"));
		href.setMatchMethod(EMatchMethod.startsWith);
		tabHrefs.add(href);
		final IAccount login = AccountSession.getLogin(requestResponse.getSession());
		href = new TabHref("关注", login == null ? LoginUtils.getLocationPath() : WebUtils.addParameters(applicationUrl, "t=attention"));
		href.setMatchMethod(EMatchMethod.startsWith);
		tabHrefs.add(href);
		href = new TabHref("我的问答", login == null ? LoginUtils.getLocationPath() : WebUtils.addParameters(applicationUrl, "t=my"));
		href.setMatchMethod(EMatchMethod.startsWith);
		tabHrefs.add(href);
		return TabsUtils.tabs(requestResponse, tabHrefs.toArray(new TabHref[tabHrefs.size()]));
	}

	@Override
	protected String getParameters(PageRequestResponse requestResponse) {
		final StringBuffer param = new StringBuffer();
		final String t = StringUtils.text(requestResponse.getRequestParameter("t"), "open");
		param.append("t=").append(t);
		final String projectId = requestResponse.getRequestParameter("projectId");
		if (StringUtils.hasText(projectId)) {
			param.append("&projectId=").append(projectId);
		}
		final String tagId = requestResponse.getRequestParameter("tagId");
		if (StringUtils.hasText(tagId)) {
			param.append("&tagId=").append(tagId);
		}
		return param.toString();
	}

	@Override
	public String tabs2(PageRequestResponse requestResponse) {
		return null;
	}

	@Override
	public String getApplicationUrl(PageRequestResponse requestResponse) {
		return "/question.html";
	}

	@Override
	public String getDeployPath() {
		return null;
	}

	@Override
	public AbstractLuceneManager createLuceneManager(ComponentParameter compParameter) {
		final File iPath = new File(compParameter.getServletContext().getRealPath(IPageConstants.DATA_HOME + "/" + "question_index"));
		IoUtils.createDirectoryRecursively(iPath);
		return new QuestionLuceneManager(compParameter, iPath);
	}

	@Override
	public ITableEntityManager getDataObjectManager() {
		return super.getDataObjectManager(QuestionBean.class);
	}

	@Override
	public IQueryEntitySet<QuestionProjectBean> queryQuestionProjectBeans(Object questionId) {
		final ITableEntityManager tMgr = getDataObjectManager(QuestionProjectBean.class);
		return tMgr.query(new ExpressionValue("questionId=?", new Object[] { questionId }), QuestionProjectBean.class);
	}

	public QuestionBean getViewQuestionBean(PageRequestResponse requestResponse) {
		final QuestionBean questionBean = getBean(QuestionBean.class, requestResponse.getRequestParameter(QuestionUtils.questionId));
		try {
			if (questionBean.checkOpen()) {
				doUpdate(new Object[] { "status" }, questionBean);
			}
			ICommonBeanAware.Utils.updateViews(requestResponse, getDataObjectManager(), questionBean);
		} catch (final Exception e) {
		}
		return questionBean;
	}

	@Override
	public void deleteAttentions(Object documentId) {
		final ITableEntityManager tMgr = getDataObjectManager(QuestionAttention.class);
		tMgr.execute(new SQLValue("delete from " + tMgr.getTablename() + " where questionId=" + documentId));
	}

	@Override
	public AbstractAttention getAttention(Object userId, Object id) {
		final ITableEntityManager tMgr = getDataObjectManager(QuestionAttention.class);
		return tMgr.queryForObject(new ExpressionValue("userId=? and questionId=?", new Object[] { userId, id }), QuestionAttention.class);
	}

}
